package org.balthie.cal.impl.calculator;

import static org.balthie.cal.core.AbsCalculator.StandardInputerKey.Ctrl_Echo;
import static org.balthie.cal.core.AbsCalculator.StandardInputerKey.Ctrl_Help;

import java.util.Optional;
import java.util.Scanner;

import org.balthie.cal.core.HelpCmd;
import org.balthie.cal.core.IInputer;

/**
 * @author：balthie@126.com
 * @createtime ： 2023年3月7日 下午1:37:55
 * @description 能够通过 Console 输入的计算器
 * @since version 初始于版本 0.0.1-SNAPSHOT
 */
public class ConsoleinteractiveCalculator extends BaseCalculator {

	public ConsoleinteractiveCalculator() {
		super();
		// 自定义指令按键
		registGenericInputer(Ctrl_Help.getKey(), new HelpCmd());
	}

	public void start() throws InterruptedException {
		println("");
		println("—————————— Console 计算器启动 ——————————");
		this.getInputer(Ctrl_Help.getKey()).get().onClick();
		println("请在Console 命令行输入指令");
		try (Scanner cin = new Scanner(System.in);) {
			boolean exit = Boolean.FALSE;
			while (!exit) {
				if (cin.hasNextLine()) {
					String n = cin.nextLine();
					Optional<IInputer> inputer = this.getInputer(n);
					if (inputer.isPresent()) {
						try {
							inputer.get().onClick();
						} catch (Exception e) {
							e.printStackTrace();
							Thread.sleep(0);
						}
					} else {
						n = n.trim();
						for (int i = 0; i < n.toCharArray().length; i++) {
							inputer = this.getInputer(String.valueOf(n.charAt(i)));
							try {
								inputer.ifPresent(in -> in.onClick());
							} catch (Exception e) {
								e.printStackTrace();
								Thread.sleep(5);
							}
						}
					}

					// 每次输入后显示 当前指令集
					this.keyboard.get(Ctrl_Echo.getKey()).onClick();

					if ("exit".equalsIgnoreCase(n)) {
						exit = Boolean.TRUE;
						clear();
					}
				}
			}
			println("——————————计算器关闭————————————");
		}
	}

}
